/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.opmviewer.core.config;

import java.util.Vector;
import java.util.prefs.Preferences;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author grzegorz
 */
public class DBRegister extends AbstractTableModel {

    private Vector<DBPair> dbList;
    Preferences dbPrefs;

    public DBRegister() {
        dbList = new Vector<DBPair>();
        Preferences prefs = Preferences.userRoot();
        dbPrefs = prefs.node("dbList");
        int listSize = dbPrefs.getInt("listSize", 0);
        for (int i = 0; i < listSize; ++i) {
            String name = dbPrefs.node("" + i).get("dbName", "");
            String loc = dbPrefs.node("" + i).get("dbLoc", "");
            dbList.add(new DBPair(name, loc));
        }
    }

    public void addDB(String dbName, String dbLoc) throws Exception {
        dbList.add(new DBPair(dbName, dbLoc));
    }

    public void removeDB(int row) throws Exception {
        dbList.remove(row);
    }

    public void save() {
        Preferences prefs = Preferences.userRoot();
        try {
            dbPrefs.removeNode();
            dbPrefs = prefs.node("dbList");
            dbPrefs.putInt("listSize", dbList.size());
            for (int i = 0; i < dbList.size(); ++i) {
                dbPrefs.node("" + i).put("dbName", dbList.get(i).dbName);
                dbPrefs.node("" + i).put("dbLoc", dbList.get(i).dbLoc);
            }
            prefs.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getValueAt(int row, int col) {
        switch (col) {
            case 0:
                return dbList.get(row).dbName;
            case 1:
                return dbList.get(row).dbLoc;
            default:
                break;
        }
        return null;
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public int getRowCount() {
        return dbList.size();
    }

    @Override
    public String getColumnName(int col) {
        switch (col) {
            case 0:
                return "Database name";
            case 1:
                return "Database location";
            default:
                return "";
        }
    }

    @Override
    public Class getColumnClass(int col) {
        return String.class;
    }
}

class DBPair {

    public DBPair(String name, String loc) {
        dbName = name;
        dbLoc = loc;
    }
    public String dbName;
    public String dbLoc;
}
